package com.nitty.cash.loop.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Build
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiCheckBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.dialog.NittySendCodeSuccessDialog
import com.nitty.cash.loop.ui.dialog.NittyBirthdayDialog
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.CheckPresenter
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import com.nitty.cash.loop.utils.log.NittyLogger
import com.nitty.cash.loop.utils.receiver.NittySMSBroadcastReceiver
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:41
 * @Annotation：账号验证页面
 */
class CheckAct: CommonActivity(), IViewContract.ICheckView{
    lateinit var binding: UiCheckBinding
    var presenter: CheckPresenter? = null
    private var sendSuccessDialog: NittySendCodeSuccessDialog? = null
    private var smsBroadcastReceiver: NittySMSBroadcastReceiver? = null

    private val SMS_CONSENT_REQUEST = 200
    var eventRemark = ""

    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 60

    //需要选择出生日期
    private var birthdayDialog: NittyBirthdayDialog? = null
    companion object {
        fun start(context: Context) {
            val intent = Intent(context, CheckAct::class.java)
            context.startActivity(intent)
        }
    }
    override fun getNittyRootView(): View? {
        binding = UiCheckBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setBackExit(true)
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#FFFAF9F9"))
        setNittyTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setNittyTitleBarVisibility(View.VISIBLE)
        setNittyBackBtnVisibility(View.GONE)
        setNittyRightBtnRes(R.mipmap.img_customer_black)
        setNittyTextTitleVisibility(View.GONE)

        initRefreshView()
        showChcekMobileTypeView(false)

        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun initNittyListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,eventRemark)
        }
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.btnSubmit.isEnabled = presenter!!.getCheckNumberSelectType().isNotEmpty() && getNittyCheckCode().isNotEmpty()
            }
        })
        binding.editMobile.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.btnConfirm.isEnabled = getNittyCheckMobile().isNotEmpty()
            }
        })

        //SMS
        binding.smsLayout.setOnClickListener {
            presenter?.setCheckNumberType("SMS")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_VERIFICATION_SMS)
        }

        //WhatsApp
        binding.whatsappLayout.setOnClickListener {
            presenter?.setCheckNumberType("WHATSAPP")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_VERIFICATION_WHATSAPP)
        }

        binding.btnSend.setOnClickListener {
            if (presenter?.getCheckNumberSelectType()!!.isEmpty()){
                return@setOnClickListener
            }
            presenter?.sendCheckNumberWhatsAppCodeAction()
        }

        binding.imgEdit.setOnClickListener {
           showChcekMobileTypeView(true)
        }
        binding.btnConfirm.setOnClickListener {
            if (getNittyCheckMobile().isEmpty()){
                return@setOnClickListener
            }
            binding.textMobile.text = getNittyCheckMobile()
            showChcekMobileTypeView(false)
        }
        //提交
        binding.btnSubmit.setOnClickListener {
            if (getNittyCheckMobile().isEmpty() || getNittyCheckCode().isEmpty()){
                binding.btnSubmit.isEnabled = false
                return@setOnClickListener
            }
            presenter?.onCheckNumberVerificationCodeAction()
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_VERIFICATION_CONTINUE,"${getNittyCheckCode()}##${getNittyCheckMobile()}")
        }
    }

    @SuppressLint("SetTextI18n")
    override fun loadNittyData() {
        presenter = CheckPresenter(this)
        val zoneCode = NittySharedHelper.getNittySharedString(NittySharedKey.NITTY_TIMEZONE_CODE)
        val mobile = NittySharedHelper.getNittySharedString(NittySharedKey.NITTY_MOBILE)
        binding.textZoneCode.text = "+$zoneCode"
        binding.textMobile.text = mobile
        binding.editMobile.setText(mobile)

        binding.btnSend.text = getString(R.string.click_send)
        binding.btnSend.isEnabled = false
        binding.smsLayout.isEnabled = true
        binding.whatsappLayout.isEnabled = true

        binding.smsLayout.visibility = View.GONE
        binding.whatsappLayout.visibility = View.GONE
        if (NittyProcessHelper.isCheckSMS()){
            binding.smsLayout.visibility = View.VISIBLE
        }
        if (NittyProcessHelper.isCheckWhatsApp()){
            binding.whatsappLayout.visibility = View.VISIBLE
        }
        showDefaultCheckTypeView()
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        smsBroadcastReceiver = NittySMSBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null,
                Context.RECEIVER_EXPORTED // 指定导出标志
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null
            )
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                NittyLogger.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                NittyLogger.e("Sms code: $code")
                if (code != null){
                    binding.editCode.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                NittyLogger.e("User canceled or no message received")
            }
        }
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        binding.checkRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.checkRefreshLayout.setOnRefreshListener {
            publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
        }
    }

    /**
     * 获取手机号
     */
    override fun getNittyCheckMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    /**
     * 获取验证码
     */
    override fun getNittyCheckCode(): String {
        return binding.editCode.text.toString().trim()
    }

    /**
     * 切换是否修改手机号View
     */
    private fun showChcekMobileTypeView(isEdit: Boolean){
        //是否允许修改手机号码
        if (!NittyProcessHelper.isMobileEditFlag()){
            binding.showMobileLayout.visibility = View.VISIBLE
            binding.imgEdit.visibility = View.GONE
            binding.showEditLayout.visibility = View.GONE
            binding.viewLine.visibility = View.INVISIBLE
            return
        }
        when(isEdit){
            true -> {
                binding.showMobileLayout.visibility = View.GONE
                binding.showEditLayout.visibility = View.VISIBLE
                binding.viewLine.visibility = View.VISIBLE
            }
            else -> {
                binding.showMobileLayout.visibility = View.VISIBLE
                binding.showEditLayout.visibility = View.GONE
                binding.viewLine.visibility = View.INVISIBLE
            }
        }
    }

    /**
     * 设置默认选中校验类型
     */
    private fun showDefaultCheckTypeView(){
        //设置默认选中：有SMS就选中SMS，否则选中WHATSAPP
        if (NittyProcessHelper.isCheckSMS()){
            presenter?.setCheckNumberType("SMS",false)
        } else {
            presenter?.setCheckNumberType("WHATSAPP",false)
        }
    }

    /**
     * 切换校验类型
     */
    override fun showNittyCheckType(type: String) {
        binding.btnSend.isEnabled = true

        binding.whatsAppIcon.setImageResource(R.mipmap.nitty_check_whatsapp_normal)
        binding.whatsAppTitle.setTextColor(Color.parseColor("#FFB4B4B4"))
        binding.whatsAppSelect.setImageResource(R.mipmap.nitty_check_type_normal)
        binding.whatsappLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFFFFFF"))
            .setStrokeColor(Color.parseColor("#FFCFCFCF"))
            .intoBackground()

        binding.imgSms.setImageResource(R.mipmap.nitty_check_sms_normal)
        binding.textSms.setTextColor(Color.parseColor("#FFB4B4B4"))
        binding.smsSelect.setImageResource(R.mipmap.nitty_check_type_normal)
        binding.smsLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFFFFFF"))
            .setStrokeColor(Color.parseColor("#FFCFCFCF"))
            .intoBackground()
        when(type){
            "SMS" -> {
                binding.imgSms.setImageResource(R.mipmap.nitty_check_sms_selected)
                binding.textSms.setTextColor(Color.parseColor("#FFFD5118"))
                binding.smsSelect.setImageResource(R.mipmap.nitty_check_type_selected)
                binding.smsLayout.shapeDrawableBuilder
                    .setSolidColor(Color.parseColor("#FFFFF4EA"))
                    .setStrokeColor(Color.parseColor("#FFFD5118"))
                    .intoBackground()
            }
            else -> {
                binding.whatsAppIcon.setImageResource(R.mipmap.nitty_check_whatsapp_selected)
                binding.whatsAppTitle.setTextColor(Color.parseColor("#FFFD5118"))
                binding.whatsAppSelect.setImageResource(R.mipmap.nitty_check_type_selected)
                binding.whatsappLayout.shapeDrawableBuilder
                    .setSolidColor(Color.parseColor("#FFFFF4EA"))
                    .setStrokeColor(Color.parseColor("#FFFD5118"))
                    .intoBackground()
            }
        }
        binding.btnSubmit.isEnabled = getNittyCheckCode().isNotEmpty()
    }

    /**
     * 验证码发送成功
     * 当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
     */
    override fun showNittyCheckSendCodeSuccess(directLoginFlag: String) {
        hiddenNittyLoading()
        when(directLoginFlag){
            "YES" -> {
                showNittyCheckSuccess()
            }
            else -> {
                startCountdownTimer()
            }
        }
    }

    /**
     * 需要选择出生日期
     */
    override fun showNittyCheckChooseBirthdayDialog() {
        if (birthdayDialog == null){
            birthdayDialog = NittyBirthdayDialog(this)
            birthdayDialog?.setCancelable(false)
            birthdayDialog?.setCanceledOnTouchOutside(false)
            birthdayDialog?.setOnClick(object : NittyBirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    presenter?.onCheckNumberVerificationCodeAction(selectDate.optString("subDate"))
                }
            })
        }
        birthdayDialog?.show()
    }


    /**
     * 校验成功
     */
    override fun showNittyCheckSuccess() {
        NittySharedHelper.putNittySharedData(NittySharedKey.NITTY_MOBILE, getNittyCheckMobile())
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 发送成功提示
     */
    private fun showSendCodeSuccessDialog(){
        if (sendSuccessDialog == null){
            sendSuccessDialog = NittySendCodeSuccessDialog(this)
            sendSuccessDialog?.setCancelable(true)
            sendSuccessDialog?.setCanceledOnTouchOutside(false)
        }
        sendSuccessDialog?.show()
        launch(Dispatchers.Main){
            delay(2000)
            sendSuccessDialog?.dismiss()
        }
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    class MyCountDownTimer(private val act: CheckAct, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showCheckCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showCheckCountdownComplete()
        }
    }

    /**
     * 倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun showCheckCountdownText(){
        binding.btnSend.text = "$countdown S"
    }

    /**
     * 倒计时完成
     */
    private fun showCheckCountdownComplete(){
        countdown = 60
        binding.btnSend.text = getString(R.string.click_send)
        binding.btnSend.isEnabled = true
        binding.smsLayout.isEnabled = true
        binding.whatsappLayout.isEnabled = true
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountdownTimer() {
        showSendCodeSuccessDialog()
        //随机 60秒 等待时长
        countdown = 60
        binding.btnSend.text = "$countdown S"
        binding.btnSend.isEnabled = false
        binding.smsLayout.isEnabled = false
        binding.whatsappLayout.isEnabled = false

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        when(event.eventType){
            NittyEventData.TYPE.NITTY_PROCESS_REFRESHED -> {
                hiddenNittyLoading()
                //需要校验 WhatsApp 或 SMS
                if (!NittyProcessHelper.isCheckWhatsApp() && !NittyProcessHelper.isCheckSMS()){
                    //校验成功
                    showNittyCheckSuccess()
                }
            }
            else -> {

            }
        }
    }

    override fun hiddenNittyLoading() {
        super.hiddenNittyLoading()
        binding.checkRefreshLayout.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "Verification Page"
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_VERIFICATION_SMS_START, eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_VERIFICATION_SMS_END, eventRemark)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        if (smsBroadcastReceiver != null){
            unregisterReceiver(smsBroadcastReceiver)
        }
    }
}